import {designPage, Fragment, nextTick, onMounted, reactive, RendererNode, watch} from "plain-design-composition";
import {$nav} from "../nav/$nav";
import {Menu, MenuGroups} from "./menus";
import Illustration from "../../../packages/components/Illustration";

export const AppContent = designPage(() => {

  const isReady = (() => {
    const flag = reactive({ value: false });
    onMounted(() => {
      setTimeout(() => flag.value = true, 1000);
    });
    return flag;
  })();

  const state = reactive({
    current: null as null | { render: () => RendererNode, name: string, title?: string, menu: Menu }
  });

  watch(() => $nav.state.route, async route => {
    const { path } = route;
    const menu = MenuGroups.map(i => i.children).flat(1).find(i => i.page === path);
    if (!menu) {
      state.current = null;
      nextTick().then(() => $nav.setScrollTop(0));
      return;
    }
    try {
      const Module = await import('../components' + menu.page);
      state.current = {
        menu,
        render: () => <>
          {Object.values(Module).map((Component, index) => (
            <Fragment key={index}>
              {/*@ts-ignore*/}
              <Component/>
            </Fragment>
          ))}
        </>,
        name: menu.name,
        title: menu.title,
      };
      nextTick().then(() => $nav.setScrollTop(0));
    } catch (e) {
      state.current = null;
      nextTick().then(() => $nav.setScrollTop(0));
    }
  }, { immediate: true });

  return () => (
    <div className="app-content">
      {!state.current ? (
        !!isReady.value && <div style={{ display: 'flex', alignItems: 'center', flexDirection: 'column' }}>
          <Illustration style={{ width: '33.33%' }} code="404"/>
          <span className="app-empty-text" style={{ fontWeight: 500, fontSize: '40px', fontFamily: 'fantasy', position: 'relative', top: '-60px' }}>404</span>
        </div>
      ) : (
        <>
          {!state.current.menu.noHeader && (
            <div style={{ fontSize: '30px', fontWeight: 500, color: 'var(--app-title-color)', marginBottom: '40px' }}>
              {state.current.name} {state.current.title}
            </div>
          )}
          {state.current.render()}
        </>
      )}
    </div>
  );
});
